package com.example.team_awesome_funf;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

import edu.mit.media.funf.FunfManager;
import edu.mit.media.funf.json.IJsonObject;
import edu.mit.media.funf.pipeline.BasicPipeline;
import edu.mit.media.funf.probe.Probe.DataListener;
import edu.mit.media.funf.probe.builtin.LocationProbe;
import edu.mit.media.funf.probe.builtin.SimpleLocationProbe;
import edu.mit.media.funf.storage.NameValueDatabaseHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements DataListener {

public static final String PIPELINE_NAME = "default";
private FunfManager funfManager;
private BasicPipeline pipeline;
private Button stopButton;
private Button testButton;
private TextView locationText;
private TextView tripText;
private LocationProbe locProbe;
private ProbeDataAnalyzer probeAnalyzer;
private int counter = 1;
private String speedText = "You have started moving \n";
private float avgSpeed = 0;
private ServiceConnection funfManagerConn = new ServiceConnection() {    
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    	
        funfManager = ((FunfManager.LocalBinder)service).getManager();  
        Gson gson = funfManager.getGson();
        locProbe = gson.fromJson(new JsonObject(), LocationProbe.class);
        pipeline = (BasicPipeline) funfManager.getRegisteredPipeline(PIPELINE_NAME);
        probeAnalyzer = new ProbeDataAnalyzer();
        locProbe.registerPassiveListener(MainActivity.this);
        // Enable the buttons, after the service connection has been established
        stopButton.setEnabled(true);
        testButton.setEnabled(true);
    }
    
    @Override
    public void onServiceDisconnected(ComponentName name) {
        funfManager = null;
    }

};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	    
	    // Initializing textviews
	    locationText = (TextView) findViewById(R.id.locationText);
	    tripText = (TextView) findViewById(R.id.tripText);
	    
	    // Setting up stop button
	    stopButton = (Button) findViewById(R.id.stopButton);
	    stopButton.setEnabled(false);
	    stopButton.setOnClickListener(new OnClickListener() {
	        @Override
	        public void onClick(View v) {
	            
	         // Update interface on main thread
	    	    runOnUiThread(new Runnable() {
	    	        @Override
	    	        public void run() {
 	    	            tripText.setText("Trip is over, with an sensed avg. speed of: " + avgSpeed/counter + " km/h " + probeAnalyzer.AnalyzeMovementSpeed(avgSpeed/counter));
 	    	            
 	    	            // Resetting textview
 	    	            locationText.setText("");
	    	        }   
	    	    });
	    	    //Resetting trip variables
	    	    counter = 1;
	            avgSpeed = 0;
	            speedText = "You have started moving:";
	        }
	    });
	    
	    // Setting up the forced test button
	    testButton = (Button) findViewById(R.id.testButton);
	    testButton.setEnabled(false);
	    testButton.setOnClickListener(new OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	//Even though no data can be registered, we force it to try
	            locProbe.registerListener(pipeline);
	        }
	    });    
	    
	    
	    // Bind to the service, to create the connection with FunfManager
	    bindService(new Intent(this, FunfManager.class), funfManagerConn, BIND_AUTO_CREATE);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onDataCompleted(IJsonObject probeConfig, JsonElement checkpoint) {
	    locProbe.registerPassiveListener(this);
	}

	@Override
	public void onDataReceived(IJsonObject arg0, IJsonObject arg1) {
		// Parsing the JSON-data
		final LocationProbeData data = probeAnalyzer.ParseLocationProbeData(arg1);
		
		// Average speeds sensed in km/h
		avgSpeed += data.Speed * 3.6;
		
		counter++;
	    runOnUiThread(new Runnable() {
	        @Override
	        public void run() {
	        	// Updating the textview with the most recent data
	        	speedText += "\n #" + counter + " Speed: " +
	        			String.valueOf(data.Speed*3.6) + " km/h " +
	        			probeAnalyzer.AnalyzeMovementSpeed((float) (data.Speed * 3.6)) + " sensed avg. speed: " +
	        			avgSpeed/counter + " km/h" ;
	            locationText.setText(speedText);
	        }   
	    });
		
		
	}

}
